// pages/mall/index.js
const app     = getApp()
const request = require('../../utils/request.js');
const config = require('../../utils/config.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        topBarHeight: 64,
        showPrivacy:false,
        nowList:{  
            total: 0,
            current_page: 0,
            last_page: 1,
            data: []
          },
          banner:[],
        contact_phone:'400-808-9577',
        region:[],
        multiArray: [],
        multiIndex: [0,0,0],
        chinaData: [],
        isTrue:false,
        privacyContractName:'新眼光健康管理小程序隐私保护指引》',
        lng:'',
        lat: '',
        longitude:'',
        latitude:''
    },
    bindMultiPickerChange: function (e) {
        this.setData({
          isTrue:true
        })
        console.log(e);
      },
      bindMultiPickerColumnChange: function (e) {
        var move = e.detail;
        var index = move.column;
        var value = move.value;
        if (index == 0) {
          this.setData({
            multiIndex: [value, 0, 0]
          })
          this.getCity();
        }
        if (index == 1) {
          this.setData({
            "multiIndex[1]": value,
            "multiIndex[2]": 0,
          })
          this.getXian();
        }
        if (index == 2) {
          this.setData({
            "multiIndex[2]": value,
    
          })
         
        }
        this.getBanner()
        this.init_Data()
       
      },
      getSiteData: function () {
        let that = this;
        var data = {};
        wx.showLoading({
          title: '加载中',
        })
        request.requestLoading(
            "/api/address/getArea",
            {},
            'POST',
          ).then((ret) => {
            var chinaData = ret.data;
            that.data.chinaData = chinaData;
            var sheng = []; //  设置省数组
            for (var i = 0; i < chinaData.length; i++) {
              sheng.push(chinaData[i].name);
            }
            that.setData({
              "multiArray[0]": sheng
            })
            that.getCity(); // 得到市
            wx.hideLoading({
                success: (res) => {},
              })
           
           
           
      
          }).catch((err) => {
            console.error(err);
          });
       
       
      },
      getCity: function () { //  得到市
        var shengNum = this.data.multiIndex[0];
        var chinaData = this.data.chinaData;
        console.log(shengNum)
        console.log(this.data.chinaData)
        var cityData = chinaData[shengNum].children;
        var city = [];
        for (var i = 0; i < cityData.length; i++) {
          city.push(cityData[i].name)
        }
        this.setData({
          "multiArray[1]": city
        })
       this.getXian()
      },
      getXian: function (e) { //  得到县
        var shengNum = this.data.multiIndex[0];
        var cityNum = this.data.multiIndex[1];
        var chinaData = this.data.chinaData;
        var xianData = chinaData[shengNum].children[cityNum].children;
        var xian = [];
        for (var i = 0; i < xianData.length; i++) {
          xian.push(xianData[i].name)
        }
        this.setData({
          "multiArray[2]": xian
        })
     
      },
    godetail(e){
        var id= e.currentTarget.dataset.id;
        wx.navigateTo({
          url: '/pages/goods_detail/index?id='+id,
        })
    },
    getBarInfo(e) {
        this.setData({
            topBarHeight: e.detail.topBarHeight
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      
        this.getSiteData()
    },
    init_Data(){
        var that = this;
        that.setData({
          'nowList.current_page': 0,
      });
      that.goodsList();
    
    
      },
      getCitys(){
        var that =this;
        if(!that.data.lng){
            app.getLocation(function (res) {
                // 经度
                console.log(res)
                var lng = res.longitude
                // 纬度
                var lat = res.latitude
                that.setData({
                  lng: lng,
                  lat: lat,
                  longitude:lng,
                  latitude:lat
                })
                that.getCurrentCitys()
               
              });
        }
    
    },
    getCurrentCitys(){
        var that =this;
        request.requestLoading(
            "/api/distance/getCurrentCity",
            {
           lat:that.data.lat,
           lng:that.data.lng
            },
            'POST',
          ).then((ret) => {
           
           if(ret.code==1){
          
            var chinaData = that.data.chinaData;
      
            var  index = that.data.multiArray[0].indexOf(ret.data.province);
         
            if(index!=-1){
                that.setData({
                    'multiIndex[0]':index
                })
                var cityData = chinaData[index].children;
                var city = [];
                for (var i = 0; i < cityData.length; i++) {
                  city.push(cityData[i].name)
                }
                that.setData({
                  "multiArray[1]": city
                })
                var  index1 = that.data.multiArray[1].indexOf(ret.data.city);
                if(index1!=-1){
                    console.log(index1)
                    that.setData({
                        'multiIndex[1]':index1,
                        isTrue:true
                    })    
                    var xianData = chinaData[index].children[index1].children;
                    var xian = [];
                    for (var i = 0; i < xianData.length; i++) {
                      xian.push(xianData[i].name)
                    }
                    that.setData({
                      "multiArray[2]": xian
                    })
                    var  index2 = that.data.multiArray[2].indexOf(ret.data.district);
                    if(index2!=-1){
                        that.setData({
                            'multiIndex[2]':index2
                        })
                       
                      
                    }
                    this.getBanner()
                    this.init_Data()  
                }
            }
           }
         
           
           
      
          }).catch((err) => {
            console.error(err);
          });
    },
    getBanner(){
        var json = {},that=this;
        json.district='';
       
      
        request.requestLoading(
            "/api/index/banner",
            json,
            'POST',
          ).then((res) => {
            that.setData({
                banner:res.data.banner
            })
            console.log(that.data.banner)
          
           
           
      
          }).catch((err) => {
            console.error(err);
          });
    },
      goodsList(){
        var json = {},that=this;
        json.nindex=that.data.nindex;
        json.keywords=that.data.keywords;
        json.district='';
        json.page = Number(that.data.nowList.current_page) + 1;
        if (json.page > 1 && that.data.nowList.current_page >= that.data.nowList.last_page) {       
            return false;
        }
        request.requestLoading(
            "/api/goods/getGoodsList",
            json,
            'POST',
          ).then((res) => {
            var nowList = res.data;
            that.setData({
                is_show:true
            })
    
            if (json.page > 1) {
                var now_nowList_data =that.data.nowList.data || [];
                var now_nowList_data = now_nowList_data.concat(nowList.data);
                nowList.data = now_nowList_data;
            }
      
            that.setData({
              nowList: nowList
            });
          
           
           
      
          }).catch((err) => {
            console.error(err);
          });
      },
      checkPrivacy(){

        wx.getPrivacySetting({
            success: res => {
              console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
              if (res.needAuthorization) {
                // 需要弹出隐私协议
                this.setData({
                  showPrivacy: true,
                  privacyContractName:res.privacyContractName
                })
               
              
            
              } else {
                  app.getLocation(function (res) {
                      // 经度
                      console.log(res)
                      var lng = res.longitude
                      // 纬度
                      var lat = res.latitude
                      that.setData({
                        lng: lng,
                        lat: lat,
                        longitude:lng,
                        latitude:lat
                      })
                     
                    });
             
              }
            },
            fail: () => {},
            complete: () => {}
          })
      
      },
      handleAgreePrivacyAuthorization() {
          this.setData({
              showPrivacy: false
            })
          app.getLocation(function (res) {
              // 经度
              console.log(res)
              var lng = res.longitude
              // 纬度
              var lat = res.latitude
              that.setData({
                lng: lng,
                lat: lat,
                longitude:lng,
                latitude:lat
              })
             
            });
       },
       togglePop3(){
          this.setData({
              showPrivacy: false
            })
       },
       handleOpenPrivacyContract() {
         // 打开隐私协议页面
         wx.openPrivacyContract({
           success: () => {}, // 打开成功
           fail: () => {}, // 打开失败
           complete: () => {}
         })
       },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.init_Data();
        this.getBanner()
    },
    gobanner(e){
        var url =e.currentTarget.dataset.url;
        if(url){
            var banner=['/pages/mall/index','pages/mine/index','pages/index/index'];
             if( banner.indexOf(url)!=-1){
                 wx.switchTab({
                   url: url,
                 })
             }else{
                 wx.navigateTo({
                   url: url,
                 })
             }
        }
   

    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.init_Data();
        this.getBanner()
        setTimeout(function(){
          wx.stopPullDownRefresh();
        },500)
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        var that =this;

        if (that.data.nowList.current_page >= that.data.nowList.last_page) {
          // functions.toast('已加载到底部了');
          return false;
      } else {
        that.goodsList();
      }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})